import Schema from 'async-validator'
import TopTip from '@/components/topTip'

export default {
  methods: {
    validate (form, descriptor) {
      return new Promise((resolve, reject) => {
        const validator = new Schema(descriptor)
        validator.validate(form, (errors, fields) => {
          if (errors) {
            // validation failed, errors is an array of all errors
            // fields is an object keyed by field name with an array of
            // errors per field
            this.showValidateErrorMessage(errors)
            reject(errors)
          }
          // validate true
          resolve()
        })
      })
    },
    showValidateErrorMessage (errors) {
      if (!Array.isArray(errors) || !errors.length) return false
      TopTip.show(errors[0].message)
    }
  }
}
